let dao = require('../dao/commonDao');
let userDao = require('../dao/userDao');
let commonDao = require('../dao/commonDao');
let async = require('async');
let pushAPI = require('../API/pushAPI');
let pomelo = require('pomelo');
let code = require('../constant/code');
let utils = require('../util/utils');
let moment = require('moment');
let logger = require('pomelo-logger').getLogger('pomelo');
let enumeration = require('../constant/enumeration');
//let redis = require('../dao/redis/redisClient');

let service = module.exports;


//检测战绩
service.checkUserAward = async function (uid, userScore, winScore, beforScore, gameType, unionID, curType) {

    let matchData = { 'uid': uid, 'endTime': "", 'gameType': gameType, 'unionID': unionID };
    let curAward = await commonDao.findOneDataFilter('userTargetModel', matchData, 'score curBureau maxBureau');
    let userType = -1;
    if (curAward) {
        let { maxBureau, curBureau, score } = curAward;
        //写入记录
        let detail = { roomID: this.roomID, createTime: Date.now(), score, beforScore, winScore, userScore, userType: curType };
        let updateDate = { $push: { detail: detail }, $inc: { curBureau: 1 } };
        if (curBureau >= maxBureau - 1) {
            updateDate.endTime = Date.now();
            updateDate.endScore = userScore;
        }
        await commonDao.updateData('userTargetModel', { '_id': curAward._id }, updateDate);
        if (curBureau * 3 > maxBureau) {

            if (score > userScore) {
                if (curBureau * 2 > maxBureau && ((score > userScore * 2 && (maxBureau - curBureau) * 3 < maxBureau) || userScore < 0 || score > userScore * 4)) {
                    userType = 5;//严重不足
                } else if (curBureau * 3 > maxBureau && score > userScore * 3) {
                    userType = 4;//有点不足
                } else if (score > userScore * 2) {
                    userType = 3;//普通不足
                } else {
                    userType = 2;//分数不足开启白名单
                }
            } else if (userScore > score * 2) {
                userType = 1;//分数太多开启黑名单
            }
        } else {
            userType = 0;
        }
    }
    return userType;
}


//玩家金币变化记录
service.addGoldScore = async function (user, detail) {

    let uid = user.uid;

    let { gameType, score, type } = detail;
    let updateUserData = { $inc: { goldScore: score } };
    let agentUser = await userDao.updateUserDataByUid(uid, updateUserData);

    if (user.userInfo && !user.userInfo.isRobot) {
        let beforeCount = user.userInfo.score || 0;
        await this.updateUserDataNotify(uid, agentUser.frontendId, { goldScore: agentUser.goldScore });
        // 创建赠送记录
        let saveData = {
            uid: agentUser.uid,
            nickname: agentUser.nickname,
            unionID: 0,
            changeCount: score,
            beforeCount: beforeCount,
            leftCount: agentUser.goldScore,
            gameType: gameType,
            changeType: type,
            describe: '金币变化',
            createTime: Date.now(),
        };
        await commonDao.createData("userScoreDetailModel", saveData).catch(e => { logger.error(e.stack) });
    }
}



service.getUserUnions = async function (userData) {

    let unionIDList = [];
    for (let i = 0; i < userData.unionInfo.length; ++i) {
        unionIDList.push(userData.unionInfo[i].unionID);
    }
    let dataArr = await commonDao.findData("unionModel", { unionID: { $in: unionIDList }, isDel: { $ne: true } });
    let recordArr = [];
    for (let i = 0; i < dataArr.length; ++i) {
        let data = dataArr[i];
        recordArr.push({

            unionInviteID: data.unionInviteID,
            unionID: data.unionID,
            unionName: data.unionName,
            ownerUid: data.ownerUid,
            ownerAvatar: data.ownerAvatar,
            ownerNickname: data.ownerNickname,
            memberCount: data.curMember,
            onlineCount: data.onlineMember,
            tableColor: data.tableColor,
            unionBg: data.unionBg,
            tableStyle: data.tableStyle,
            emptyTable: data.emptyTable,
            isInvite: data.isInvite,
            unionSkinId: data.unionSkinId,
            unionType: data.unionType,
            unionGameType: data.unionGameType,
            disApplyCount: data.disApplyCount,
            inviteLimit: data.inviteLimit,
            joinVerify: data.joinVerify,
            propsLimit: data.propsLimit,
            tableHideCount: data.tableHideCount,
            unReadyKick: data.unReadyKick,
            groupLimit: data.groupLimit,
            gameLimited: data.gameLimited,
            tableSort: data.tableSort,
            isTeamData: data.isTeamData,
            isUserData: data.isUserData,
            isScoreData: data.isScoreData,
            unionOpen: data.opening,
            opening: data.opening,
            dismissType: data.dismissType
        })
    }
    return recordArr;
}



service.getRebateTotal = async function (userList, dayTime, unionID) {

    //计算返利明细
    let todayTimeStart = moment(dayTime).startOf('day').format('x');
    let todayTimeEnd = moment(dayTime).endOf('day').format('x');
    //查询数据
    let matchData = {
        createTime: { $gte: parseInt(todayTimeStart), $lte: parseInt(todayTimeEnd) },
        uid: { $in: userList },
        unionID: unionID
    };
    let groupData = { _id: '$unionID', total: { $sum: "$gainCount" } };
    let execData = [
        {
            $match: matchData
        },
        {
            $group: groupData
        }
    ];
    let result = await commonDao.getStatisticsInfo('userRebateRecordModel', execData);
    return result.length > 0 ? result[0].total : 0;
}

service.checkUserLimit = async function (unionID, uid, gameRuleID) {

    let resultCode = code.OK;

    let matchData = { uid: { '$in': [uid, -1] }, unionID: unionID };
    let gameLimit = [];
    let limit = await commonDao.findData("gameLimitModel", matchData);
    for (let key in limit) {
        gameLimit = gameLimit.concat(limit[key].list || []);
    }
    if (gameLimit.includes(gameRuleID)) {
        resultCode = code.ROOM_JOIN_FAIL;
    }
    return resultCode;
}


//检查禁止同桌
service.checkGameLimit = async function (unionID, userInfo, unionLimit, type = []) {

    let resultCode = code.OK;

    if (type.includes(4)) {
        //同IP玩家不能同桌
        let ipList = [];
        for (let key in unionLimit) {
            if (unionLimit[key].ip) {
                ipList.push(unionLimit[key].ip);
            }
        }
        if (userInfo.lastLoginIP && ipList.includes(userInfo.lastLoginIP)) {
            resultCode = code.UNION_GAME_LIMIT_IP;
        }
    }

    if (type.includes(1)) {
        //直属成员不能同桌
        let spreaderList = [];
        for (let key in unionLimit) {
            spreaderList.push(unionLimit[key].spreaderID);
            spreaderList.push(unionLimit[key].uid);
        }
        if (spreaderList.includes(userInfo.spreaderID) || spreaderList.includes(userInfo.uid)) {
            resultCode = code.UNION_GAME_LIMIT_ZHI;
        }
    }

    if (type.includes(2)) {
        //同分支成员不能同桌
        let userList = await service.getUnionAllUser(unionID);
        let spreaderList = [];
        for (let key in unionLimit) {
            let curList = await service.getSuperWithoutOwner(unionLimit[key].uid, unionID, userList);
            curList.push(unionLimit[key].uid);
            spreaderList = spreaderList.concat(curList);
        }
        let curSuper = await service.getSuperWithoutOwner(userInfo.uid, unionID, userList);
        curSuper.push(userInfo.uid);
        if (curSuper.find(item => spreaderList.includes(item))) {
            resultCode = code.UNION_GAME_LIMIT_FEN;
        }
    }

    if (type.includes(3)) {
        //同分支跨两家不能同桌



    }



    return resultCode;

}



//获取玩家所有上级
service.getSuperWithoutOwner = async function (userID, unionID, allUnionList = null) {

    if (!allUnionList) {
        allUnionList = await service.getUnionAllUser(unionID);
    }
    let allUserList = allUnionList.slice();
    let userData = allUserList.find(item => item.uid == userID);
    let curSuperID = userData.spreaderID;
    let superList = [];
    if (userData) {
        //查找下级
        let isHaveNext = true;
        while (isHaveNext && curSuperID && curSuperID != '') {
            let superUser = allUserList.find(item => item.uid == curSuperID);
            if (superUser) {
                curSuperID = superUser.spreaderID;
                if (curSuperID == '') {
                    isHaveNext = false;
                } else {
                    superList.push(superUser.uid);
                }
            } else {
                isHaveNext = false;
            }
        }
    }
    return superList;
}


//检查禁止同桌
service.checkBlockUser = async function (unionID, userID, curUserID) {

    let resultCode = code.OK;

    let unionData = await dao.findOneData('unionModel', { unionID: unionID });
    if (unionData && !unionData.groupLimit) {

        let matchData = {
            unionID: unionID,
            $and: [{ userList: { $elemMatch: { uid: userID } } }, {
                userList: { $elemMatch: { uid: { $in: curUserID } } }
            }]
        };
        let blockUser = await commonDao.findOneData('userBlockModel', matchData);
        if (blockUser) {
            resultCode = code.USER_BLOCK_LIMITE;
        }
    }
    return resultCode;

}



//获取玩家加入房间警戒线
service.getLimitScore = async function (unionID, userID) {

    let userList = await service.getUnionAllUser(unionID);
    let curUser = userList.find(item => item.uid == userID);
    //获取当前玩家的所有上级
    let allSuper = await service.getUserSuperAll(userID, unionID, userList);
    if (curUser.partner) {
        //如果是代理 则要检查自己的团队
        allSuper.unshift(userID);
    }
    let userLevelList = allSuper.slice();
    let resultCode = code.OK;
    for (let i = 0; i < userLevelList.length; i++) {

        let superUserID = userLevelList[i];
        let curSuper = userList.find(item => item.uid == superUserID);
        //如果没有设置警戒则查询上级
        if (!curSuper.limitScore) continue;
        //如果设置了警戒线
        let lowUserScoreAll = await service.getUserLowScoreAll(superUserID, unionID, userList);
        if (lowUserScoreAll < curSuper.limitScore) {
            resultCode = code.UNION_GAME_ENTER_LIMIT_SCORE;
            break;
        }
    }
    return resultCode;

}


//通过战绩获取分数
service.getTodayUserScore = async function (unionID, userList, dayTime) {


    let startTime = moment(dayTime).startOf('d').format('x');
    let endTime = moment(dayTime).endOf('d').format('x');
    let matchData = {
        'userList.uid': {
            $in: userList
        },
        'unionID': unionID,
        'createTime': {
            $gte: startTime,
            $lte: endTime
        }
    };
    let todayWin = 0;
    let todayDraw = 0;
    let totalRecord = await commonDao.findData('userGameRecordModel', matchData);
    for (let i = 0; i < totalRecord.length; i++) {

        let curDetail = totalRecord[i];
        let curUserList = curDetail.userList;
        for (let k = 0; k < curUserList.length; k++) {
            let scoreDetail = curUserList[k];
            if (userList.includes(scoreDetail.uid)) {
                todayWin += scoreDetail.score;
                todayDraw += 1;
            }
        }
    }
    return {
        todayDraw,
        todayWin
    };

};


//重新计算联盟的玩家分数
service.getTodayUserScoreBack = async function (unionID, userList, dayTime) {


    //游戏赢分 返利 门票  
    let typeList = [enumeration.scoreChangeType.FIX_SCORE, enumeration.scoreChangeType.GAME_WIN_CHOU, enumeration.scoreChangeType.GAME_WIN, enumeration.scoreChangeType.SAFE_BOX, enumeration.scoreChangeType.GAME_START_UNION_CHOU];
    let startTime = moment(dayTime).startOf('d').format('x');
    let endTime = moment(dayTime).endOf('d').format('x');
    let matchData = {
        uid: {
            $in: userList
        },
        'unionID': unionID,
        'changeType': {
            $in: typeList
        },
        'createTime': {
            $gte: startTime,
            $lte: endTime
        }
    };
    let groupData = {
        _id: '$uid',
        score: {
            $sum: "$changeCount"
        }
    };
    let execData = [{
        $match: matchData
    },
    {
        $group: groupData
    }
    ];
    let todayWin = 0;
    let todayDraw = 0;
    let scoreList = await commonDao.getStatisticsInfo('userScoreDetailModel', execData);
    for (let i = 0; i < scoreList.length; i++) {
        let curData = scoreList[i];
        let uid = curData._id;
        let score = parseFloat(curData.score.toFixed(2)) || 0;
        let curUser = await userDao.getUserDataByUid(uid);
        let userUnionInfoItem = curUser.unionInfo.find(function (element) {
            return element.unionID === unionID;
        });
        todayWin += score;
        if (dayTime == moment().format('YYYYMMDD')) {
            todayDraw += userUnionInfoItem.todayDraw;
        } else {
            todayDraw += userUnionInfoItem.yesterdayDraw;
        }

    }
    return {
        todayDraw,
        todayWin
    };

};

//重新计算联盟的玩家分数
service.reCountUserScore = async function (unionID, dayTime) {

    //游戏赢分 返利 门票  
    let typeList = [enumeration.scoreChangeType.FIX_SCORE, enumeration.scoreChangeType.GAME_WIN_CHOU, enumeration.scoreChangeType.GAME_WIN, enumeration.scoreChangeType.SAFE_BOX, enumeration.scoreChangeType.GAME_START_UNION_CHOU];
    let startTime = moment(dayTime).startOf('d').format('x');
    let endTime = moment(dayTime).endOf('d').format('x');
    let matchData = {
        'unionID': unionID,
        'changeType': {
            $in: typeList
        },
        'createTime': {
            $gte: startTime,
            $lte: endTime
        }
    };
    let groupData = {
        _id: '$uid',
        score: {
            $sum: "$changeCount"
        }
    };
    let execData = [{
        $match: matchData
    },
    {
        $group: groupData
    }
    ];
    let scoreList = await commonDao.getStatisticsInfo('userScoreDetailModel', execData);
    for (let i = 0; i < scoreList.length; i++) {
        let curData = scoreList[i];
        let uid = curData._id;
        let score = curData.score.toFixed(2);
        let curUser = await userDao.getUserDataByUid(uid);
        let nickname = curUser.nickname;
        let avatar = curUser.avatar;
        let userUnionInfoItem = curUser.unionInfo.find(function (element) {
            return element.unionID === unionID;
        });
        let userScore = (userUnionInfoItem && userUnionInfoItem.score || 0).toFixed(2);
        let saveScore = (userUnionInfoItem && userUnionInfoItem.saveScore || 0).toFixed(2);
        let saveData = {
            unionID,
            uid,
            score,
            nickname,
            userScore,
            saveScore,
            avatar,
            dayTime,
            createTime: moment().format('x')
        };
        await commonDao.updateDataEx("userScoreModel", {
            uid,
            unionID,
            dayTime
        }, saveData, {
            upsert: true
        }).catch(err => {
            logger.error(err);
        });
    }
    return scoreList.length;

};


service.createUserThenLoad = async function (uid, userInfo) {

    let idIndex = utils.getRandomNum(1, 10);
    let saveData = {};
    saveData.uid = uid;
    saveData.gold = parseInt(pomelo.app.get("config")["startGold"] || '0');
    saveData.avatar = userInfo.avatar || "morentouxiang" + idIndex;
    saveData.avatarFrame = "";
    saveData.nickname = userInfo.nickname || saveData.uid.toString();
    saveData.sex = userInfo.sex || 0;
    saveData.createTime = Date.now();

    await dao.createData('userModel', saveData);
    return await userDao.getUserDataByUid(uid);
};

service.updateUserDataNotify = async function (uid, sid, updateUserData) {
    if (!uid) return;
    if (!!sid) {
        await pushAPI.updateUserInfoPush(updateUserData, [{
            uid: uid,
            sid: sid
        }]);
    } else {
        let userData = await userDao.getUserDataByUid(uid);
        if (!userData || !userData.frontendId || userData.isRobot) return;
        await pushAPI.updateUserInfoPush(updateUserData, [{
            uid: uid,
            sid: sid
        }]);
    }
};

service.getNewUserEmail = function (userEmail, lastLoginTime) {
    let emailArr = userEmail.length > 0 ? JSON.parse(userEmail) : [];
    let config = pomelo.app.get('config');
    // 删除过期邮件
    let isEmailUpdate = false;
    let newEmailArr = [];
    for (let i = 0; i < emailArr.length; ++i) {
        let emailInfo = emailArr[i];
        if (utils.getIntervalDay(emailInfo.createTime, Date.now()) < 7) {
            newEmailArr.push(emailArr[i]);
        } else {
            isEmailUpdate = true;
        }
    }
    let lastUpdateSystemEmailTime = parseInt(config["lastUpdateSystemEmailTime"]);
    // 检查是否有新的系统邮件
    if (lastLoginTime > 0 && lastUpdateSystemEmailTime > 0 && lastUpdateSystemEmailTime > lastLoginTime) {
        if (!!config["systemEmail"]) {
            let systemEmailArr = JSON.parse(config["systemEmail"]);
            for (let i = 0; i < systemEmailArr.length; ++i) {
                let systemEmailInfo = systemEmailArr[i];
                let isExist = false;
                for (let j = 0; j < emailArr.length; ++j) {
                    if (emailArr[j].id === systemEmailInfo.id) {
                        isExist = true;
                        break;
                    }
                }
                if (!isExist && utils.getIntervalDay(systemEmailInfo.createTime, Date.now()) < 7) {
                    newEmailArr.push(systemEmailInfo);
                    isEmailUpdate = true;
                }
            }

        }
    }
    return isEmailUpdate ? JSON.stringify(newEmailArr) : null;
};

service.convertMongoUserDataToRedisUserData = function (userData) {
    if (!userData) return null;
    let redisUserData = {};
    for (let key in userData) {
        if (key === '_id') continue;
        if (userData.hasOwnProperty(key)) {
            if (typeof userData[key] !== 'string' && key !== '$inc') {
                redisUserData[key] = userData[key].toString();
            } else {
                redisUserData[key] = userData[key];
            }
        }
    }
    return redisUserData;
};

service.convertRedisUserDataToMongoUserData = function (userData) {
    let schema = pomelo.app.get('dbClient')['userModel'].schema.tree;
    let redisUserData = {};
    for (let key in userData) {
        if (userData.hasOwnProperty(key)) {
            let schemaKey = schema[key];
            if (!!schemaKey && !!schemaKey.type && schemaKey.type.name === 'Number') {
                redisUserData[key] = parseFloat(userData[key]);
            } else {
                redisUserData[key] = userData[key];
            }
        }
    }
    return redisUserData;
};

service.buildShortUserInfo = function (userInfo) {
    let shortUserInfo = {};
    if ('nickname' in userInfo) shortUserInfo.nickname = userInfo.nickname;
    if ('avatar' in userInfo) shortUserInfo.avatar = userInfo.avatar;
    if ('uid' in userInfo) shortUserInfo.uid = userInfo.uid;
    if ('sex' in userInfo) shortUserInfo.sex = userInfo.sex;
    return shortUserInfo;
};

service.buildShortMemberInfo = function (userInfo) {
    return {
        uid: userInfo.uid,
        nickname: userInfo.nickname,
        avatar: userInfo.avatar,
        achievement: userInfo.achievement,
        lastLoginTime: userInfo.lastLoginTime
    };
};

service.buildShortAgentInfo = function (userInfo) {
    return {
        uid: userInfo.uid,
        nickname: userInfo.nickname,
        avatar: userInfo.avatar,
        directlyMemberAchievement: userInfo.directlyMemberAchievement,
        agentMemberAchievement: userInfo.agentMemberAchievement,
        directlyMemberCount: userInfo.directlyMemberCount,
        agentMemberCount: userInfo.agentMemberCount,
        lastLoginTime: userInfo.lastLoginTime
    };
};

service.buildGameRoomUserInfo = function (userInfo) {
    let buildUserInfo = {};
    if ('uid' in userInfo) buildUserInfo.uid = userInfo.uid;
    if ('nickname' in userInfo) buildUserInfo.nickname = userInfo.nickname;
    if ('avatar' in userInfo) buildUserInfo.avatar = userInfo.avatar;
    if ('gold' in userInfo) buildUserInfo.gold = userInfo.gold;
    if ('frontendId' in userInfo) buildUserInfo.frontendId = userInfo.frontendId;
    if ('unionInfo' in userInfo) buildUserInfo.unionInfo = userInfo.unionInfo;
    if ('address' in userInfo) buildUserInfo.address = userInfo.address;
    if ('location' in userInfo) buildUserInfo.location = userInfo.location;
    if ('lastLoginIP' in userInfo) buildUserInfo.lastLoginIP = userInfo.lastLoginIP;
    if ('sex' in userInfo) buildUserInfo.sex = userInfo.sex;
    if ('isTest' in userInfo) buildUserInfo.isTest = userInfo.isTest;
    if ('isRobot' in userInfo) buildUserInfo.isRobot = userInfo.isRobot || false;
    if ('winRate' in userInfo) buildUserInfo.winRate = userInfo.winRate || 0;
    if ('winType' in userInfo) buildUserInfo.winType = userInfo.winType || 0;
    if ('userType' in userInfo) buildUserInfo.userType = userInfo.userType || 0;
    if ('goldScore' in userInfo) buildUserInfo.score = userInfo.goldScore;
    if ('robotTest' in userInfo && userInfo.robotTest == 1) buildUserInfo.isTest = 1;

    for (let key in buildUserInfo) {
        if (buildUserInfo.hasOwnProperty(key)) {
            return buildUserInfo;
        }
    }
    return null;
};

service.buildGameRoomUserInfoWithUnion = function (userInfo, unionID) {
    let buildUserInfo = {};
    if ('uid' in userInfo) buildUserInfo.uid = userInfo.uid;
    if ('nickname' in userInfo) buildUserInfo.nickname = userInfo.nickname;
    if ('avatar' in userInfo) buildUserInfo.avatar = userInfo.avatar;
    if ('gold' in userInfo) buildUserInfo.gold = userInfo.gold;
    if ('frontendId' in userInfo) buildUserInfo.frontendId = userInfo.frontendId;
    if ('address' in userInfo) buildUserInfo.address = userInfo.address;
    if ('location' in userInfo) buildUserInfo.location = userInfo.location;
    if ('lastLoginIP' in userInfo) buildUserInfo.lastLoginIP = userInfo.lastLoginIP;
    if ('sex' in userInfo) buildUserInfo.sex = userInfo.sex;
    if ('isTest' in userInfo) buildUserInfo.isTest = userInfo.isTest;
    if ('isRobot' in userInfo) buildUserInfo.isRobot = userInfo.isRobot || false;
    if ('winRate' in userInfo) buildUserInfo.winRate = userInfo.winRate || 0;
    if ('winType' in userInfo) buildUserInfo.winType = userInfo.winType || 0;
    if ('robotTest' in userInfo && userInfo.robotTest == 1) buildUserInfo.isTest = 1;
    // if ('userType' in userInfo) buildUserInfo.userType = userInfo.userType || 0;
    if ('score' in userInfo) buildUserInfo.score = userInfo.score;
    // 普通房间
    if (unionID === 1) {
        if (!userInfo.goldRoom) {
            buildUserInfo.score = 0;
            buildUserInfo.spreaderID = "";
            buildUserInfo.userType = userInfo.userType || 0;
        }
    } else {
        if ('unionInfo' in userInfo) {
            let unionInfoItem = userInfo.unionInfo.find(function (ele) {
                return ele.unionID === unionID;
            });
            if (!!unionInfoItem) {
                buildUserInfo.score = parseFloat(unionInfoItem.score.toFixed(2));
                buildUserInfo.spreaderID = unionInfoItem.spreaderID;
                buildUserInfo.prohibitGame = unionInfoItem.prohibitGame || false;
                buildUserInfo.targetScore = unionInfoItem.targetScore || 0;
                buildUserInfo.floatScore = unionInfoItem.floatScore || 0;
                buildUserInfo.userType = unionInfoItem.userType || 0;
            } else {
                buildUserInfo.score = 0;
                buildUserInfo.spreaderID = "";
                buildUserInfo.prohibitGame = false;
                buildUserInfo.targetScore = 0;
                buildUserInfo.floatScore = 0;
                buildUserInfo.userType = 0;
            }
        }
    }

    for (let key in buildUserInfo) {
        if (buildUserInfo.hasOwnProperty(key)) {
            return buildUserInfo;
        }
    }
};

//获取用户数据
service.getUserDataTotal = async (unionID, userList, isRebate = true) => {


    return new Promise((resolve, reject) => {

        let query = {
            uid: {
                $in: userList
            }
        };
        async.waterfall([

            async (cb) => {
                let userData = await dao.findData('userModel', query, {
                    "unionInfo.todayWin": -1
                }, 0, 0);
                let totalCount = 0; //总人数
                let totalScore = 0; //总分数
                let yesterdayDrawTotal = 0; //昨日局数
                let todayDrawTotal = 0; //今日局数
                let todayTotalRebate = 0; //今日返利
                let yesterdayTotalRebate = 0; //今日返利
                let todayTotalProvideRebate = 0; //昨日
                let yesterdayTotalProvideRebate = 0; //昨日
                let totalDraw = 0;
                let todayWinTotal = 0;
                let yesterdayWinTotal = 0;
                let todayTotalRebateBack = 0;
                let yesterdayTotalRebateBack = 0;
                for (let i = 0; i < userData.length; i++) {

                    if (userData[i]) {
                        let unionInfoItem = userData[i].unionInfo.find(function (ele) {
                            return ele.unionID === unionID;
                        });
                        if (unionInfoItem) {
                            totalCount += 1;
                            //分数要加上保险柜的分数
                            todayDrawTotal += parseInt(unionInfoItem.todayDraw.toFixed(2)) || 0;
                            yesterdayDrawTotal += parseInt(unionInfoItem.yesterdayDraw.toFixed(2)) || 0;
                            todayWinTotal += parseFloat(unionInfoItem.todayWin.toFixed(2)) || 0;
                            yesterdayWinTotal += parseFloat(unionInfoItem.yesterdayWin.toFixed(2)) || 0;
                            totalScore += parseFloat(unionInfoItem.score) || 0;
                            totalScore += parseFloat(unionInfoItem.safeScore) || 0;
                            totalScore += parseFloat(unionInfoItem.saveScore) || 0;
                            todayTotalProvideRebate += parseFloat(unionInfoItem.todayProvideRebate.toFixed(2)) || 0;
                            yesterdayTotalProvideRebate += parseFloat(unionInfoItem.yesterdayProvideRebate.toFixed(2)) || 0;
                            todayTotalRebateBack += parseFloat(unionInfoItem.todayRebate.toFixed(2)) || 0;
                            yesterdayTotalRebateBack += parseFloat(unionInfoItem.yesterdayRebate.toFixed(2)) || 0;
                            totalDraw += parseInt(unionInfoItem.totalDraw) || 0;
                        } else {
                            console.log(userData[i]);
                        }
                    }
                }
                if (isRebate) {
                    //计算返利明细
                    let todayTimeStart = moment().startOf('day').format('x');
                    let todayTimeEnd = moment().endOf('day').format('x');
                    let yesterDayTimeStart = moment().add(-1, 'd').startOf('day').format('x');
                    let yesterDayTimeEnd = moment().add(-1, 'd').endOf('day').format('x');
                    //查询数据
                    let matchData = {
                        createTime: {
                            $gte: parseInt(todayTimeStart),
                            $lte: parseInt(todayTimeEnd)
                        },
                        uid: {
                            $in: userList
                        },
                        unionID: unionID
                    };
                    let groupData = { _id: '$unionID', total: { $sum: "$gainCount" } };
                    let execData = [
                        {
                            $match: matchData
                        },
                        {
                            $group: groupData
                        }
                    ];
                    let result = await commonDao.getStatisticsInfo('userRebateRecordModel', execData);
                    todayTotalRebate = result.length > 0 ? result[0].total : 0;
                    let matchData2 = {
                        createTime: {
                            $gte: parseInt(yesterDayTimeStart),
                            $lte: parseInt(yesterDayTimeEnd)
                        },
                        uid: {
                            $in: userList
                        },
                        unionID: unionID
                    };
                    let execData2 = [
                        {
                            $match: matchData2
                        },
                        {
                            $group: groupData
                        }
                    ];
                    let result2 = await commonDao.getStatisticsInfo('userRebateRecordModel', execData2);
                    yesterdayTotalRebate = result2.length > 0 ? result2[0].total : 0;
                    // let recordArr = await commonDao.findData('userRebateRecordModel', matchData, {
                    //     createTime: -1
                    // }, 0, 0);
                    // for (let j = 0; j < recordArr.length; j++) {
                    //     let curTime = parseInt(recordArr[j].createTime);
                    //     if (curTime >= parseInt(todayTimeStart) && curTime <= parseInt(todayTimeEnd)) {
                    //         todayTotalRebate += recordArr[j].gainCount;
                    //     } else if (curTime >= yesterDayTimeStart && curTime <= yesterDayTimeEnd) {
                    //         yesterdayTotalRebate += recordArr[j].gainCount;
                    //     }
                    // }
                }
                totalScore = Math.floor(totalScore * 100) / 100;
                cb(null, {
                    todayTotalRebate,
                    yesterdayTotalRebate,
                    totalCount,
                    totalScore,
                    yesterdayDrawTotal,
                    todayDrawTotal,
                    yesterdayTotalProvideRebate,
                    totalDraw,
                    todayWinTotal,
                    yesterdayWinTotal
                });
            }

        ], (err, result) => {
            if (err) {
                reject(code.FAIL);
            } else {
                resolve(result);
            }
        });


    });

}

//获取联盟所有的玩家
service.getUnionAllUser = async function (unionID) {

    //  let allUserList = await redis.getValue('UNION_' + unionID);
    let allUserList = null;
    if (allUserList) {
        allUserList = JSON.parse(allUserList);
    } else {
        allUserList = [];
        let allUserMatch = {
            unionInfo: {
                $elemMatch: {
                    unionID: unionID
                }
            }
        };
        let allUser = await commonDao.findData('userModel', allUserMatch, null, 0, 0);

        for (let k = 0; k < allUser.length; k++) {
            let userData = allUser[k];
            // 判断是否在联盟中
            let userUnionInfoItem = userData.unionInfo.find(function (element) {
                return element.unionID === unionID;
            });
            //用户基础信息
            let {
                uid,
                nickname,
                avatar,
                isAgent,
                userType,
                isTest
            } = userData;
            //联盟基础信息
            let {
                spreaderID,
                score,
                saveScore,
                showFixScore,
                partner,
                rebateRate,
                manager,
                limitScore,
                targetScore,
                floatScore
            } = userUnionInfoItem;
            let userInfo = {
                uid,
                nickname,
                score,
                saveScore,
                avatar,
                isAgent,
                userType,
                isTest,
                spreaderID,
                showFixScore,
                partner,
                rebateRate,
                manager,
                limitScore,
                targetScore,
                floatScore
            };
            allUserList.push(userInfo);
        }
    }
    return allUserList;
}

//获取玩家所有下级分数
service.getUserLowScoreAll = async function (userID, unionID, allUnionList = null) {

    if (!allUnionList) {
        allUnionList = await service.getUnionAllUser(unionID);
    }
    let allUserList = allUnionList.slice();
    let userData = allUserList.find(item => item.uid == userID);
    let score = (userData.score || 0) + (userData.saveScore || 0);
    if (userData) {
        //查找下级
        let isHaveNext = true;
        let superList = [userData.uid];
        while (isHaveNext) {
            let nextUser = allUserList.filter(item => superList.includes(item.spreaderID));
            if (nextUser.length > 0) {
                superList = [];
                nextUser.map(item => {
                    superList.push(item.uid);
                    score += item.score || 0;
                    score += item.saveScore || 0;
                })
            } else {
                isHaveNext = false;
            }
        }
    }
    return score;
}

//获取玩家所有下级
service.getUserLowAll = async function (userID, unionID, allUnionList = null) {

    if (!allUnionList) {
        allUnionList = await service.getUnionAllUser(unionID);
    }
    let allUserList = allUnionList.slice();
    let userData = allUserList.find(item => item.uid == userID);
    let lowUserList = [userID];
    if (userData) {
        //查找下级
        let isHaveNext = true;
        let superList = [userData.uid];
        while (isHaveNext) {
            let nextUser = allUserList.filter(item => superList.includes(item.spreaderID));
            if (nextUser.length > 0) {
                superList = [];
                nextUser.map(item => {
                    superList.push(item.uid);
                    lowUserList.push(item.uid);
                })
            } else {
                isHaveNext = false;
            }
        }
    }
    return lowUserList;
}

//获取玩家所有上级
service.getUserSuperAll = async function (userID, unionID, allUnionList = null) {

    if (!allUnionList) {
        allUnionList = await service.getUnionAllUser(unionID);
    }
    let allUserList = allUnionList.slice();
    let userData = allUserList.find(item => item.uid == userID);
    let curSuperID = userData.spreaderID;
    let superList = [];
    if (userData) {
        //查找下级
        let isHaveNext = true;
        while (isHaveNext && curSuperID && curSuperID != '') {
            let superUser = allUserList.find(item => item.uid == curSuperID);
            if (superUser) {
                superList.push(superUser.uid);
                curSuperID = superUser.spreaderID;
                if (curSuperID == '') {
                    isHaveNext = false;
                }
            } else {
                isHaveNext = false;
            }
        }
    }
    return superList;
}

//获取玩家上级对象
service.getSPreadLevelAsync = function (userId, unionID) {


    return new Promise((resolve, reject) => {
        //logger.error(`获取玩家层级关系开始 userId = ${userId} unionID = ${unionID} `);
        let userLevelList = [];
        let count = 0;
        let isEnd = false;
        async.doUntil(
            async (cb) => {
                // 先执行
                let userData = await userDao.getUserDataByUid(userId);
                count += 1;
                if (userData) {
                    let newUserInfo = userData.unionInfo.find(function (e) {
                        return e.unionID === unionID;
                    });
                    if (newUserInfo) {
                        //继续查找上级
                        let spreaderID = newUserInfo.spreaderID;
                        let rebateRate = newUserInfo.rebateRate;
                        let fixScoreRate = newUserInfo.fixScoreRate;
                        let ticketRate = newUserInfo.ticketRate || 0;
                        let result = {
                            userId,
                            spreaderID,
                            rebateRate,
                            ticketRate,
                            count,
                            fixScoreRate
                        };
                        userLevelList.push(result);
                        if (newUserInfo.spreaderID == '' || !newUserInfo.spreaderID) {
                            isEnd = true;
                        } else {
                            userId = newUserInfo.spreaderID;
                        }
                    } else {
                        isEnd = true;
                    }
                } else {
                    isEnd = true;
                }
                if (count > 100) {
                    //防止死循环
                    isEnd = true;
                }
                cb(null, userId);
            },
            () => {
                return isEnd;
            }, // 后验证
            (err, value) => {
                if (err) {
                    reject([]);
                } else {
                    resolve(userLevelList);
                }
            }
        );

    });

}

//获取所有玩家详情
service.getAllUserDetail = async function (userList, unionID) {


    let query = { uid: { $in: userList } };
    let userData = await dao.findData('userModel', query, { "uid": -1 }, 0, 0);
    let totalCount = 0; //总人数
    let totalScore = 0; //总分数
    let rebateScore = 0;
    for (let i = 0; i < userData.length; i++) {

        if (userData[i]) {
            let unionInfoItem = userData[i].unionInfo.find(item => item.unionID == unionID);
            if (unionInfoItem) {
                totalCount += 1;
                //分数要加上保险柜的分数
                totalScore += parseFloat(unionInfoItem.score) || 0;
                totalScore += parseFloat(unionInfoItem.saveScore) || 0;
                rebateScore += parseFloat(unionInfoItem.safeScore) || 0;
            } else {
                console.log(userData[i]);
            }
        }
    }
    totalScore = parseFloat(totalScore.toFixed(2));
    rebateScore = parseFloat(rebateScore.toFixed(2));
    return { totalCount, totalScore, rebateScore };

}